﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ProgNetAppBlocks.Forms;
using ProgNetComponents.Data;
using ProgNetDxComponents.Controls.Forms;
using ProgNetDxComponents.ExtenderProviders.Browsers;
using ProgNet.Constants;
using ProgNetDxComponents.ExtenderProviders.Options;

namespace MiniKsiegowosc.Wrk.Ksiegi.VatS
{
    public partial class FormWrkVatS : ProgNetSpreadSheetForm
    {
        private bool LockEvents = false;
        InputFormText _InputFormText;
        private InputFormText InputFormText
        {
            get
            {
                if (_InputFormText == null)
                {
                    _InputFormText = new InputFormText();
                    _InputFormText.ValidateValue += new EventHandler<ValidationEventArgs>(_InputFormText_ValidateValue);
                }
                return _InputFormText;
            }
        }

        void _InputFormText_ValidateValue(object sender, ValidationEventArgs e)
        {
            if (e.Value.AsString().Trim().IsNull())
            {
                e.Error = "Podaj nazwę";
            }
            else if (BrowserCache.IsDisplayValueValid(BrowserNames.StpVatS, e.Value))
            {
                e.Error = "Nazwa jest już zajęta";
            }
        }
        public FormWrkVatS()
        {
            InitializeComponent();
        }
        public FormWrkVatS(int rok)
        {
            InitializeComponent();
            CurrentRecordId = rok;
        }
        protected override void FinishEdit()
        {
            base.FinishEdit();
            DataRow[] rows = wrkVatSDataSet.WRK_VATS.Select();
            foreach (DataRow row in rows)
            {
                row.SetColumnValue("WRK_VATS_ROK", row["WRK_VATS_DATA_WYSTAWIENIA"].AsDateTime().Year);
            }
        }
        protected override ProgNetComponents.Data.ObjectKeyValuePair[] GetOpenParameters()
        {
            ObjectKeyValuePair k = new ObjectKeyValuePair("@ROK", CurrentRecordId);
            return new ObjectKeyValuePair[] { k };
        }
        protected override string FormText
        {
            get
            {
                return base.FormText + " Rok: " + CurrentRecordId.AsString();
            }
        }
        private void gvMain_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            if (!LockEvents)
            {
                LockEvents = true;
                if (e.Value.IsNotNull())
                {
                    if (e.Column == colWRK_VATS_DATA_WYSTAWIENIA)
                    {
                        object current = e.Value;
                        if (current == null)
                            gvMain.SetRowCellValue(e.RowHandle, colMiesiac, -1);
                        else
                        {
                            gvMain.SetRowCellValue(e.RowHandle, colMiesiac, current.AsDateTime().Month);
                        }
                        if (gvMain.GetRowCellValue(e.RowHandle, colWRK_VATS_DATA_SPRZEDAZY).IsNull())
                        {
                            gvMain.SetRowCellValue(e.RowHandle, colWRK_VATS_DATA_SPRZEDAZY, e.Value);
                        }
                    }
                    if (e.Column == colWRK_VATS_DATA_SPRZEDAZY)
                    {
                        if (gvMain.GetRowCellValue(e.RowHandle, colWRK_VATS_DATA_WYSTAWIENIA).IsNull())
                        {
                            gvMain.SetRowCellValue(e.RowHandle, colWRK_VATS_DATA_WYSTAWIENIA, e.Value);
                            object current = e.Value;
                            if (current == null)
                                gvMain.SetRowCellValue(e.RowHandle, colMiesiac, -1);
                            else
                            {
                                gvMain.SetRowCellValue(e.RowHandle, colMiesiac, current.AsDateTime().Month);
                            }
                        }
                    }
                }
                LockEvents = false;
            }
        }

        private void BrowserSettings_AdditionalBrowserValueChanging(object sender, DevExpress.XtraEditors.Controls.ChangingEventArgs e)
        {
            e.Cancel = true;
            DataRow r = gvMain.GetFocusedDataRow();
            WrkTools.AddVatSFromPredef(wrkVatSDataSet, e.NewValue.AsInt(), r);
        }
        List<DataRow> list = new List<DataRow>();
        protected override bool ValidateRow(DataRow r, DevExpress.XtraGrid.Views.Grid.GridView gv)
        {
            bool result = base.ValidateRow(r, gv);
            if (gv == gvMain)
            {
                if (r["WRK_VATS_DATA_WYSTAWIENIA"].IsNotNull())
                {
                    DateTime d = r["WRK_VATS_DATA_WYSTAWIENIA"].AsDateTime();
                    if (d.Year != CurrentRecordId.AsInt())
                    {
                        list.Add(r);
                    }
                    if (!WrkTools.IsRokValid(d.Year))
                    {
                        r.SetColumnError("WRK_VATS_DATA_WYSTAWIENIA", "Brak Roku Księgowego.");
                        AddError("Brak Roku Księgowego " + d.Year);
                        result = false;
                    }
                }
            }
            return result;
        }

        protected override void ValidateAll()
        {
            list.Clear();
            base.ValidateAll();

            if (list.Count > 0)
            {
                if (this.ShowDxYNQuestionDialog("Nie wszystkie wpisy są z roku " + CurrentRecordId.AsString() + ".\nChcesz zapisać?") != System.Windows.Forms.DialogResult.Yes)
                {
                    AddError("Nie wszystkie wpisy są z roku " + CurrentRecordId.AsString());
                    foreach (DataRow r in list)
                    {
                        r.SetColumnError("WRK_VATS_DATA_WYSTAWIENIA", "Zły rok.");
                    }
                }
            }

            foreach (DataRow r in list)
                gvMain.ExpandRow(r);
        }
        protected override bool Save()
        {
            Manager.AutoCommit = false;
            bool result = base.Save();
            if (result && OptionCache.GetOptionBoolValue(OptionNames.AddVatSToKpir))
            {
                result = WrkTools.AddVatSToKpir(wrkVatSDataSet, Manager);
                if (!result)
                {
                    this.ShowDxErrorDialog("Błąd dodawania faktur do KPiR.");
                }
            }
            if (result)
                Manager.Commit();
            else
                Manager.Rollback();
            return result;
        }
        private void bbiPrint_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            RaportTools.FormMonthRaportPrint.ShowPrintDialog(CurrentRecordId.AsInt(), new raportVatS());
        }

        private void bbiDodajDoKPiR_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {

        }

        private void bbiZapiszJako_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (gcMain.FocusedView != null)
            {
                gcMain.FocusedView.CloseEditor();
                gcMain.FocusedView.UpdateCurrentRow();
            }

            DataRow row = gvMain.GetFocusedDataRow();
            if (row != null)
            {
                ObjectDialogResult dlg = InputFormText.ShowInputDialog("Nazwa:");
                if (dlg.DialogResult == System.Windows.Forms.DialogResult.OK)
                {
                    string msg = "";
                    bool result = WrkTools.SaveVatSAsPredef(row, dlg.Value.AsString(), ref msg);
                    if (!result)
                    {
                        if (msg.IsNull())
                            msg = "Błąd zapisu.";
                        this.ShowDxErrorDialog(msg);
                    }
                    else
                    {
                        this.ShowDxInfoDialog("Faktura zapisana jako wzór.");
                    }
                }
            }
        }
    }
}
